package cn.virens.packet;

import java.io.Serializable;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class DBPacketSimple implements DBPacket, Serializable {
	private static final long serialVersionUID = -6822239667642317832L;
	private final AtomicInteger counter = new AtomicInteger(); // 计数器

	private String cmd; // 命令值
	private String mac; // 接收地址
	private String data; // 数据包

	@Override
	public String cmd() {
		return cmd;
	}

	public void cmd(String cmd) {
		this.cmd = cmd;
	}

	@Override
	public String mac() {
		return mac;
	}

	public void mac(String mac) {
		this.mac = mac;
	}

	@Override
	public String data() {
		return data;
	}

	public void data(String data) {
		this.data = data;
	}

	@Override
	public JSONObject json() {
		return JSON.parseObject(data);
	}

	public void json(JSONObject json) {
		this.data = json.toString();
	}

	public void json(JSONArray json) {
		this.data = "{\"array\":" + json.toString() + "}";
	}

	@Override
	public int counterGet() {
		return counter.get();
	}

	@Override
	public boolean counterTimeout(int timeout) {
		return counter.incrementAndGet() > timeout;
	}

	@Override
	public boolean equals(Object obj) {
		return Objects.hashCode(obj) == hashCode();
	}

	@Override
	public int hashCode() {
		return Objects.hash(mac, cmd);
	}

	@Override
	public String toString() {
		return "DBPacketSimple [cmd=" + cmd + ", mac=" + mac + ", data=" + data + "]";
	}
}
